﻿using System.Collections.Generic;
using System.IO;
using Wolfpack.Periscope.Core.Interfaces;
using Wolfpack.Periscope.Core.Interfaces.Entities;

namespace Wolfpack.Periscope.Core.Infrastructure
{
    public class DefaultWidgetScriptCache : IWidgetScriptCache
    {
        public IEnumerable<string> LoadSamples()
        {
            throw new System.NotImplementedException();
        }

        public IEnumerable<Property> WriteSample(WidgetInstance instance, string content)
        {
            string href;
            WriteFile(instance.Id, "txt", content, out href);
            return new Property[0];
        }

        public IEnumerable<Property> WriteScript(WidgetInstance instance, string content)
        {
            string href;
            if (!WriteFile(instance.Id, "js", content, out href))
                return new Property[0];

            return new[]
            {
                new Property
                {
                    Name = string.Format("{0}Script", instance.Id),
                    Value = href
                }
            };
        }

        public IEnumerable<Property> WriteCss(WidgetInstance instance, string content)
        {
            string href;
            if (!WriteFile(instance.Id, "css", content, out href))
                return new Property[0];

            return new[]
            {
                new Property
                {
                    Name = string.Format("{0}Stylesheet", instance.Id),
                    Value = href
                }
            };
        }

        private static bool WriteFile(string name, string fileExt, string content, out string href)
        {
            href = null;
            if (string.IsNullOrWhiteSpace(content))
                return false;

            var filename = string.Format(@"widgets\_cache\{0}.{1}", name, fileExt);
            href = "/" + filename.Replace("\\", "/");

            Directory.CreateDirectory(Path.GetDirectoryName(filename) ?? string.Empty);
            using (var sw = new StreamWriter(filename, false))
            {
                sw.Write(content);
                return true;
            }
        }
    }
}